<template>
  <div>
    <!-- 操作按钮 -->
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      "
    >
      <div>
        <a-button type="primary" @click="showModal" style="margin-right: 10px">
          新增
        </a-button>
        <a-button type="primary" danger @click="deleteSelect">删除</a-button>
      </div>
      <div style="display: flex; align-items: center">
        <!-- 多个搜索框与按钮在同一行显示 -->
        <a-input
          v-model:value="query.name"
          placeholder="姓名"
          style="width: 100px; margin-right: 10px"
        />
        <a-input
          v-model:value="query.username"
          placeholder="账号"
          style="width: 100px; margin-right: 10px"
        />
        <a-select
          v-model:value="query.roles"
          style="width: 100px; margin-right: 10px"
          placeholder="角色"
        >
          <a-select-option value="admin">admin</a-select-option>
          <a-select-option value="editor">editor</a-select-option>
          <a-select-option value="test">test</a-select-option>
        </a-select>
        <!-- 添加更多搜索框，根据需要 -->

        <!-- 查询按钮 -->
        <a-button
          type="primary"
          @click="handleTableChange"
          style="margin-right: 10px"
        >
          查询
        </a-button>
        <a-button type="primary" @click="clearSearch">清空</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :row-key="(record) => record.id"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <!-- 使用插槽来渲染操作列 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'ability'">
          <span>
            <a-tag
              v-for="elment in record.ability"
              :key="elment"
              :color="
                elment == 'READ'
                  ? 'green'
                  : elment == 'WRITE'
                  ? '#ffbb96'
                  : '#f44d77'
              "
            >
              {{ elment }}
            </a-tag>
          </span>
        </template>
        <template v-if="column.key === 'avatar'">
          <span>
            <a-image :width="40" :src="record.avatar" />
          </span>
        </template>
        <template v-if="column.dataIndex === 'roles'">
          <span>
            <a-tag
              v-for="elment in record.roles"
              :key="elment"
              :color="elment == 'admin' ? 'skyblue' : 'green'"
            >
              {{ elment }}
            </a-tag>
          </span>
        </template>
        <template v-if="column.key === 'action'">
          <span>
            <a @click="showUpdatePassword(record.id)">修改密码</a>
            <a-divider type="vertical" />
            <a @click="update(record.id)">编辑</a>
            <a-divider type="vertical" />
            <a @click="_delete(record.id)">删除</a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 新增/修改 -->
    <a-modal
      v-model:open="visible"
      title="新增用户"
      centered
      @ok="add"
      wrap-class-name="full-modal"
    >
      <form>
        <a-form
          :model="formData"
          :label-col="{ style: { width: '150px' } }"
          :wrapper-col="{ span: 14 }"
        >
          <a-form-item
            label="头像"
            :rules="[{ required: true, message: '头像不能为空!' }]"
          >
            <a-upload
              v-model:file-list="fileList"
              name="image"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <img
                v-if="formData.avatar"
                :src="formData.avatar"
                alt="avatar"
                style="width: 100px; height: 100px"
              />
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item
            label="姓名"
            :rules="[{ required: true, message: '请输入姓名!' }]"
          >
            <a-input v-model:value="formData.name" placeholder="请输入姓名" />
          </a-form-item>
          <a-form-item
            label="账号"
            :rules="[{ required: false, message: '请输入账号!' }]"
          >
            <a-input
              v-model:value="formData.username"
              placeholder="请输入账号"
            />
          </a-form-item>
          <!-- 密码不需要编辑 -->
          <a-form-item
            v-if="!formData.id"
            label="密码"
            :rules="[{ required: true, message: '请输入密码!' }]"
          >
            <a-input-password
              v-model:value="formData.password"
              placeholder="请输入密码"
            />
          </a-form-item>
          <a-form-item label="角色" name="roles">
            <a-select
              v-model:value="formData.roles"
              placeholder="请选择你的角色"
            >
              <a-select-option value="admin">admin</a-select-option>
              <a-select-option value="editor">editor</a-select-option>
              <a-select-option value="test">test</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="权限">
            <a-checkbox-group v-model:value="formData.ability">
              <a-checkbox value="READ" name="type">READ</a-checkbox>
              <a-checkbox value="WRITE" name="type">WRITE</a-checkbox>
              <a-checkbox value="DELETE" name="type">DELETE</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
          <a-form-item
            label="个性签名"
            :rules="[{ required: false, message: '请输入个性签名!' }]"
          >
            <a-input
              v-model:value="formData.introduction"
              placeholder="请输入个性签名"
            />
          </a-form-item>
        </a-form>
      </form>
    </a-modal>
    <!-- 修改密码 -->
    <a-modal
      v-model:open="visiblePassword"
      title="修改密码"
      centered
      @ok="updatePassword"
      wrap-class-name="full-modal"
    >
      <form>
        <a-form
          :model="formData"
          :label-col="{ style: { width: '150px' } }"
          :wrapper-col="{ span: 14 }"
        >
          <a-form-item
            label="密码"
            :rules="[{ required: true, message: '请输入密码!' }]"
          >
            <a-input-password
              v-model:value="passwordData.password"
              placeholder="请输入密码"
            />
          </a-form-item>
          <a-form-item
            label="确认密码"
            :rules="[{ required: true, message: '请输入确认密码!' }]"
          >
            <a-input-password
              v-model:value="passwordData.enterPassword"
              placeholder="请输入密码"
            />
          </a-form-item>
        </a-form>
      </form>
    </a-modal>
  </div>
</template>

<script>
  import {
    getList,
    _delete,
    add,
    get,
    update,
    updatePassword,
  } from '@/api/user'
  import { fileUpload } from '@/api/common'
  import { Modal } from 'ant-design-vue'
  import { message } from 'ant-design-vue'
  import moment from 'moment'

  // 定义列的字段
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '账号',
      dataIndex: 'username',
    },
    {
      title: '头像',
      key: 'avatar',
      dataIndex: 'avatar',
    },
    {
      title: '角色',
      dataIndex: 'roles',
    },
    {
      title: '个性签名',
      dataIndex: 'introduction',
    },
    {
      title: '权限',
      key: 'ability',
      dataIndex: 'ability',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      customRender: (text) => {
        return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      customRender: (text) => {
        return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
      },
    },
    {
      title: '操作',
      key: 'action', // 自定义渲染操作列
      fixed: 'right', // 固定右侧
    },
  ]
  export default {
    data() {
      return {
        data: [], // 列表数据
        pagination: {
          showLessItems: true,
          showQuickJumper: true,
          showSizeChanger: true,
        }, // 分页参数
        query: {}, //查询参数
        loading: false, // 是否加载
        columns, // 表格列
        selectedRowKeys: [], // 选中的列
        visible: false, // 显示新增删除框
        formData: {}, // 新增删除的数据框
        visiblePassword: false, // 显示修改密码框
        passwordData: {}, // 修改密码的
        fileList: [],
      }
    },
    computed: {
      hasSelected() {
        return this.selectedRowKeys.length > 0
      },
    },
    mounted() {
      this.fetch()
    },
    methods: {
      // 上传图片
      beforeUpload(file) {
        const formData = new FormData()
        formData.append('image', file)
        formData.append('label', 'avatar')
        fileUpload(formData).then((data) => {
          this.formData.avatar = data.data
        })
        console.log(file)
        return true
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
        }
        if (info.file.status === 'done') {
          // 上传完成后的操作
          this.loading = false

          // 从后台返回的响应中获取文件访问路径
          const response = info.file.response
          if (response && response.url) {
            this.formData.avatar = response.url
          }
        }
        if (info.file.status === 'error') {
          // 上传出错时的操作
          this.loading = false
        }
      },
      updatePassword() {
        if (this.passwordData.password != this.passwordData.enterPassword) {
          message.error('两次输入的密码不相同')
          return
        }
        updatePassword(this.passwordData).then(() => {
          this.visiblePassword = false
        })
      },
      // 打开编辑密码框
      showUpdatePassword(id) {
        this.visiblePassword = true
        this.passwordData = { id: id }
      },
      // 打开新增框
      showModal() {
        this.visible = true
        this.formData = {
          roles: 'admin',
          ability: ['READ', 'WRITE', 'DELETE'],
        }
      },
      // 修改数据
      update(id) {
        get({ id: id }).then(({ data }) => {
          // 查询单个展示
          this.formData = { ...data }
          // 角色由于存储限制，此处需要转一下
          this.formData.roles = data.rolesArray[0]
          this.formData.ability = JSON.parse(data.ability)
          this.visible = true
        })
      },
      // 选择
      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        this.selectedRowKeys = selectedRowKeys
      },
      // 删除选中
      deleteSelect() {
        this._delete(this.selectedRowKeys)
      },
      // 删除数据
      _delete(id) {
        let ids
        // 此处批量跟单个删除公用，做一下判断
        if (Array.isArray(id)) {
          ids = id
        } else {
          ids = [id]
        }
        if (ids && ids.length > 0) {
          Modal.confirm({
            title: 'Confirm',
            content: '确定要删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              _delete(ids).then(() => {
                // 删除就清空勾选项
                this.selectedRowKeys = []
                // 重新查询数据
                this.handleTableChange(this.pagination)
              })
            },
          })
        }
      },
      // 清空查询参数
      clearSearch() {
        Object.getOwnPropertyNames(this.query).forEach((key) => {
          this.query[key] = null
        })
        this.handleTableChange(this.pagination)
      },
      // 新增/修改数据
      add() {
        // 复制一份数据
        const _formData = { ...this.formData }
        // 角色此处是单选，但是后台存的是数组
        _formData.roles = [_formData.roles]
        // 存在id走修改
        if (_formData.id) {
          update(_formData).then(() => {
            this.visible = false
            this.handleTableChange(this.pagination)
          })
        } else {
          add(_formData).then(() => {
            this.visible = false
            this.handleTableChange(this.pagination)
          })
        }
      },
      // 查询数据
      handleTableChange(pagination) {
        const pager = { ...this.pagination }
        pager.current = pagination.current
        this.pagination = pager
        this.fetch()
      },
      // 请求后台
      fetch() {
        this.loading = true
        getList({
          pageSize: this.pagination.pageSize,
          current: this.pagination.current,
          ...this.query,
        }).then(({ data }) => {
          const pagination = { ...this.pagination }
          pagination.total = data.total
          this.loading = false
          this.data = data.records
          // 给数组列加一些特效
          for (const key in this.data) {
            if (Object.hasOwnProperty.call(this.data, key)) {
              this.data[key].ability = JSON.parse(this.data[key].ability)
              this.data[key].roles = JSON.parse(this.data[key].roles)
            }
          }
          console.log(this.data)
          this.pagination = pagination
        })
      },
    },
  }
</script>
<style></style>
